package cc.uncarbon.module.appapi.service;

import cc.uncarbon.framework.core.context.TenantContext;
import cc.uncarbon.framework.core.context.TenantContextHolder;
import cc.uncarbon.framework.core.exception.BusinessException;
import cc.uncarbon.framework.core.props.HelioProperties;
import cc.uncarbon.module.appapi.constant.WxMiniAppConstant;
import cc.uncarbon.module.appapi.mapper.UserMapper;

import cc.uncarbon.module.appapi.model.request.UserLoginDTO;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.protobuf.ServiceException;
import com.yanrumiao.entity.UserEntity;
import com.yanrumiao.enumns.AppErrorEnum;
import com.yanrumiao.enumns.UserStatusEnum;
import com.yanrumiao.util.HttpClientUtil;
import com.yanrumiao.util.PwdUtil;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.http.HttpClient;
import java.util.HashMap;
import java.util.Map;

import static cn.hutool.http.ContentType.JSON;


/**
 * 用户信息
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class UserService {

    private final UserMapper userMapper;
    @Autowired
    private WxMiniAppConstant wxAppConstant;
    private final HelioProperties helioProperties;

    private boolean isTenantEnabled;

    @PostConstruct
    public void postConstruct() {
        this.isTenantEnabled = helioProperties.getTenant().getEnabled();
    }


    public UserEntity login(UserLoginDTO dto) {

        if (isTenantEnabled && ObjectUtil.isNotNull(dto.getTenantId())) {
            TenantContext tenantContext = TenantContext.builder()
                    .tenantId(dto.getTenantId())
                    .build();
            // 验证通过，将所属租户写入租户上下文，使得 SQL 拦截器可以正确执行
            TenantContextHolder.setTenantContext(tenantContext);
        }

        System.out.println(dto.toString()+"---------------------");
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", dto.getPhone());

        UserEntity user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            throw new BusinessException(AppErrorEnum.INCORRECT_PIN_OR_PWD);
        }
        if (!PwdUtil.encrypt(dto.getPassword(), user.getSalt()).equals(user.getPassword())) {
            throw new BusinessException(AppErrorEnum.INCORRECT_PIN_OR_PWD);
        }
        if (UserStatusEnum.BANNED == user.getStatus()) {
            throw new BusinessException(AppErrorEnum.BANNED_USER);
        }


        return user;
    }

    public UserEntity loginwx(String code) {
        String openid = doAuth(
                wxAppConstant.getUrl(),
                wxAppConstant.getAppId(),
                wxAppConstant.getAppSecret(),
                code).get("openid");


        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wx_open_id", openid);
        UserEntity user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            user = new UserEntity();
            user.setWxOpenId(openid);
            userMapper.insert(user);
            user = userMapper.selectById(user.getId());
        }
        TenantContext tenantContext = new TenantContext();
        if (isTenantEnabled && ObjectUtil.isNotNull(user.getTenantId())) {
            tenantContext.setTenantId(user.getTenantId());
            // 验证通过，将所属租户写入租户上下文，使得 SQL 拦截器可以正确执行
            TenantContextHolder.setTenantContext(tenantContext);
        }

        return user;

    }

    public Map<String, String> doAuth(String url, String appid, String secret, String code) {
        String getMessageUrl = url + "?appid=" + appid + "&secret=" + secret + "&js_code=" + code
                + "&grant_type=authorization_code";

        String result = HttpClientUtil.sendHttpGet(getMessageUrl);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject.containsKey("openid")) {
            String openid = jsonObject.getStr("openid");
            String sessionKey = jsonObject.getStr("session_key");
            return new HashMap<String, String>() {
                {
                    put("openid", openid);
                    put("sessionKey", sessionKey);
                }
            };
        } else {
            throw new BusinessException(AppErrorEnum.BANNED_USER);
        }
    }
}
